package service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.example.menhoo.menhoolibrary.R;
import com.example.menhoo.toollibrary.common.assist.Network;
import com.lidroid.xutils.util.LogUtils;

import org.ddpush.im.util.DateTimeUtil;
import org.ddpush.im.util.StringUtil;
import org.ddpush.im.v1.client.appuser.Message;
import org.ddpush.im.v1.client.appuser.TCPClientBase;
import org.ddpush.im.v1.client.appuser.UDPClientBase;
import org.ddpush.im.v1.client.appuser.example.MyUdpClient;

import java.nio.ByteBuffer;

import application.UIApplication;
import receiver.TickAlarmReceiver;

/**
 * Created by yanglei on 15/12/13.
 */
public class UDPPushService extends UIService {
    public static String DEFAULT_PRE_NAME= UIApplication.PackageName;
    public static String SERVER_IP="serverIP";
    public static String SERVER_PORT="serverPort";
    public static String DEVICE_ID="deviceID";
    public static String APP_ID="appID";
    protected PendingIntent tickPendIntent;
    PowerManager.WakeLock wakeLock;
    MyUdpClient myUdpClient;
    Notification n;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public class MyUdpClient extends UDPClientBase{

        public MyUdpClient(byte[] uuid, int appid, String serverAddr, int serverPort)
                throws Exception {
            super(uuid, appid, serverAddr, serverPort);

        }

        @Override
        public boolean hasNetworkConnection() {
            return Network.isAvailable(UDPPushService.this);
        }

        @Override
        public void trySystemSleep() {
            tryReleaseWakeLock();
        }

        @Override
        public void onPushMessage(Message message) {
            if(message == null){
                return;
            }
            if(message.getData() == null || message.getData().length == 0){
                return;
            }
            LogUtils.e("收到推送消息了 ~~~~~~~~~");

            if(message.getCmd() == 16){// 0x10 通用推送信息
                notifyUser(16,"通用信息","时间："+ DateTimeUtil.getCurDateTime(),"收到通用推送信息");
            }
            if(message.getCmd() == 17){// 0x11 分组推送信息
                long msg = ByteBuffer.wrap(message.getData(), 5, 8).getLong();
                notifyUser(17,"分组推送信息",""+msg,"收到通用推送信息");
            }
            if(message.getCmd() == 32){// 0x20 自定义推送信息
                String str = null;
                try{
                    str = new String(message.getData(),5,message.getContentLength(), "UTF-8");
                }catch(Exception e){
                    str = StringUtil.convert(message.getData(),5,message.getContentLength());
                }
                notifyUser(32,"文本信息",""+str,"收到自定义推送信息");
            }
        }
    }

    protected void tryReleaseWakeLock(){
        if(wakeLock != null && wakeLock.isHeld() == true){
            wakeLock.release();
        }
    }

    protected void resetClient(){
        SharedPreferences account = this.getSharedPreferences(DEFAULT_PRE_NAME, Context.MODE_PRIVATE);
        String serverIp = account.getString(SERVER_IP, "");
        String serverPort = account.getString(SERVER_PORT, "");
        String deviceID = account.getString(DEVICE_ID, "");
        int appID = account.getInt(APP_ID,1);
        if(serverIp == null || serverIp.trim().length() == 0
                || serverPort == null || serverPort.trim().length() == 0
                || deviceID == null || deviceID.trim().length() == 0){
            return;
        }
        if(this.myUdpClient != null){
            try{myUdpClient.stop();}catch(Exception e){}
        }
        try{
            myUdpClient = new MyUdpClient(StringUtil.md5Byte(deviceID), appID, serverIp, Integer.parseInt(serverPort));
            myUdpClient.setHeartbeatInterval(10);
            myUdpClient.start();

        }catch(Exception e){
            Toast.makeText(this.getApplicationContext(), "操作失败：" + e.getMessage(), Toast.LENGTH_LONG).show();
        }
        //Toast.makeText(this.getApplicationContext(), "ddpush：终端重置", Toast.LENGTH_LONG).show();
        LogUtils.i("ddpush：终端重置");
    }

    protected void setTickAlarm(){
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this,TickAlarmReceiver.class);
        int requestCode = 0;
        tickPendIntent = PendingIntent.getBroadcast(this,
                requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        //小米2s的MIUI操作系统，目前最短广播间隔为5分钟，少于5分钟的alarm会等到5分钟再触发！2014-04-28
        long triggerAtTime = System.currentTimeMillis();
        int interval = 60 * 1000;
        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, interval, tickPendIntent);
    }

    protected void cancelTickAlarm(){
        AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmMgr.cancel(tickPendIntent);
    }

    @Override
    public int onStartCommand(Intent param, int flags, int startId) {
        if(param == null){
            return START_STICKY;
        }
        String cmd = param.getStringExtra("CMD");
        if(cmd == null){
            cmd = "";
        }
        if(cmd.equals("TICK")){
            if(wakeLock != null && wakeLock.isHeld() == false){
                wakeLock.acquire();
            }
            resetClient();
        }
        if(cmd.equals("RESET")){
            if(wakeLock != null && wakeLock.isHeld() == false){
                wakeLock.acquire();
            }
            resetClient();
        }
        if(cmd.equals("TOAST")){
            String text = param.getStringExtra("TEXT");
            if(text != null && text.trim().length() != 0){
                Toast.makeText(this, text, Toast.LENGTH_LONG).show();
            }
        }

        return START_STICKY;
    }

    protected void notifyRunning(){
//        NotificationManager notificationManager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
//        n = new Notification();
//        Intent intent = new Intent(this,MainActivity.class);
//        PendingIntent pi = PendingIntent.getActivity(this, 0,intent, PendingIntent.FLAG_ONE_SHOT);
//        n.contentIntent = pi;
//        n.setLatestEventInfo(this, "DDPushDemoTCP", "正在运行", pi);
//        //n.defaults = Notification.DEFAULT_ALL;
//        //n.flags |= Notification.FLAG_SHOW_LIGHTS;
//        //n.flags |= Notification.FLAG_AUTO_CANCEL;
//        n.flags |= Notification.FLAG_ONGOING_EVENT;
//        n.flags |= Notification.FLAG_NO_CLEAR;
//        //n.iconLevel = 5;
//
//        n.icon = R.drawable.ic_launcher;
//        n.when = System.currentTimeMillis();
//        n.tickerText = "DDPushDemoTCP正在运行";
//        notificationManager.notify(0, n);
    }

    protected void cancelNotifyRunning(){
        NotificationManager notificationManager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancel(0);
    }

    public void notifyUser(int id, String title, String content, String tickerText){

        Notification n =new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(content)
                .setTicker(tickerText)
                .setSmallIcon(R.drawable.ic_launcher)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setVibrate(new long[]{0, 500, 100, 500})
                .build();
        NotificationManager notificationManager=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(id,n);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //this.cancelTickAlarm();
        cancelNotifyRunning();
        this.tryReleaseWakeLock();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        this.setTickAlarm();

        PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "PushService");

//        int wifiSleepValue= Settings.System.getInt(getContentResolver(),Settings.System.WIFI_SLEEP_POLICY,Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
//        //设定为“总是”
//        Settings.System.putInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY,Settings.System.WIFI_SLEEP_POLICY_NEVER);

        resetClient();

    }


}
